package client;


import org.apache.ignite.Ignition;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.client.IgniteClient;
import org.apache.ignite.configuration.ClientConfiguration;
import other.IgniteJobConfig;
import other.IgniteUtil;
import other.Person;

import java.util.List;
import java.util.Scanner;

public class SqlTest {

    private static final String DML = "CREATE TABLE City (" +
            " id LONG PRIMARY KEY, name VARCHAR) " +
            " WITH \"template=replicated\"";


    public static void main(String[] args) {
        IgniteJobConfig igniteJobConfig = IgniteUtil.parseConfig();
        ClientConfiguration clientConfiguration = IgniteUtil.init(igniteJobConfig.getUri());

        Scanner scanner = new Scanner(System.in);

        try (IgniteClient client = Ignition.startClient(clientConfiguration)) {
            dropTable(client);
            System.out.println("即将执行建表操作,请按回车确认:" +
                    "CREATE TABLE IF NOT EXISTS Person (\n" +
                    "id INT PRIMARY KEY, name VARCHAR" +
                    ") WITH \"VALUE_TYPE=PUBLIC\")");
//            scanner.nextLine();
            createTable(client);
            System.out.println("即将插入数据 name字段固定为\"张三\"，id自增，请输入插入条数：");
            String num = scanner.nextLine();
            for (int i = 0; i < Integer.valueOf(num); i++) {
                insertIntoPerson(client, i, "张三");
            }
            System.out.println("即将查询数据，请选择查询的id：");
            String id = scanner.nextLine();
            selectPerson(client, id);

            System.out.println("即将删除数据，请选择删除的id：");
            String id1 = scanner.nextLine();
            deletePerson(client, id1);

            System.out.println("即将获取全量数据");
//            scanner.nextLine();
            selectAllPerson(client);

            System.out.println("即将清除表");
            dropTable(client);
            System.out.println("清除表: DROP TABLE IF EXISTS Person");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createTable(IgniteClient client) {
        client.query(new SqlFieldsQuery(String.format(
                "CREATE TABLE IF NOT EXISTS Person (id INT PRIMARY KEY, name VARCHAR) WITH \"VALUE_TYPE=%s\"",
                Person.class.getName())).setSchema("PUBLIC")).getAll();
    }

    private static void dropTable(IgniteClient client) {
        FieldsQueryCursor<List<?>> dropTableIfExistsPerson = client.query(new SqlFieldsQuery("DROP TABLE IF EXISTS Person"));
        List<List<?>> all = dropTableIfExistsPerson.getAll();
        all.forEach(System.out::println);

    }

    private static void insertIntoPerson(IgniteClient client, Integer id, String name) {
        Person val = new Person(id, name);

        client.query(new SqlFieldsQuery("INSERT INTO Person(id, name) VALUES(?, ?)").setArgs(val.getId(), val.getName())
                .setSchema("PUBLIC")).getAll();
        System.out.println("插入数据成功: INSERT INTO Person(id, name) VALUES(" + id + "," + name + ")");
    }


    private static void selectPerson(IgniteClient client, String id) {
        FieldsQueryCursor<List<?>> cursor = client
                .query(new SqlFieldsQuery("SELECT id,name from Person WHERE id=?").setArgs(id).setSchema("PUBLIC"));
        // Get the results; the `getAll()` methods closes the cursor; you do not have to
        // call cursor.close();
        List<List<?>> results = cursor.getAll();

        results.forEach(columns -> {
            System.out.println("id: " + columns.get(0) + " name: " + columns.get(1));
        });
        System.out.println("查询完毕：SELECT id,name from Person WHERE id=" + id);
    }

    private static void selectAllPerson(IgniteClient client) {
        FieldsQueryCursor<List<?>> cursor = client
                .query(new SqlFieldsQuery("SELECT id,name from Person").setSchema("PUBLIC"));
        // Get the results; the `getAll()` methods closes the cursor; you do not have to
        // call cursor.close();
        List<List<?>> results = cursor.getAll();

        results.forEach(columns -> {
            System.out.println("id: " + columns.get(0) + " name: " + columns.get(1));
        });
        System.out.println("查询完毕：SELECT id,name from Person");
    }

    private static void deletePerson(IgniteClient client, String id) {
        List<List<?>> results = client
                .query(new SqlFieldsQuery("DELETE from Person WHERE id >= ?")
                        .setArgs(Long.valueOf(id))
                        .setSchema("PUBLIC"))
                .getAll();

// Get the results; the `getAll()` methods closes the cursor; you do not have to
// call cursor.close();
//        List<List<?>> results = cursor.getAll();

        results.forEach(System.out::println);

        System.out.println("删除成功：delete from Person WHERE id >=" + id);
    }
}
